package com.zl.controller;

import com.zl.pojo.Order;
import com.zl.pojo.OrderDetail;
import com.zl.pojo.User;
import com.zl.service.LoginService;
import com.zl.service.OrderDetailService;
import com.zl.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private OrderService os;
    @Autowired
    private OrderDetailService ods;
    @Autowired
    private LoginService ls;
    @RequestMapping("/login")
    public String UserLogin(User user, String isLogin, HttpServletResponse response, HttpSession session){
        user =ls.login(user);
        if (user!=null){
            if("login".equals(isLogin)){
                //创建cookie对象
                Cookie ck1 = new Cookie("name", user.getLoginName());
                Cookie ck2=new Cookie("pwd",user.getPassword());
                //设置cookie保存时间
                ck1.setMaxAge(60*60*24);
                ck2.setMaxAge(60*60*24);
                System.out.println(ck2.getValue());
                System.out.println(ck1.getValue());
                //设置cookie保存路径
                ck1.setPath("/YiMaiWangTest");
                ck2.setPath("/YiMaiWangTest");
                //将cookie发送到客户端
                response.addCookie(ck1);
                response.addCookie(ck2);

            }
            List<Order> orders= os.queryOrderByUserId(user.getId());
            Order oo= orders.get(0);
            List<OrderDetail> order=ods.queryById(oo.getId());
            int num=order.size();
            Double cost=ods.queryOrderCostByOrderId(oo.getId());
            session.setAttribute("user",user);//保存user对象
            session.setAttribute("cost",cost);
            session.setAttribute("order",order);
            session.setAttribute("num",num);
            return "redirect:/index/news";
        }else {
            return  "login/Login";
        }
    }
}
